/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package flight.client;

import flight.model.Flight;
import flight.model.FlightList;
import flight.service.FlightService;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import middleware.Callback;
import middleware.Naming;

/**
 *
 * @author VU MINH TAM
 */
public class FlightClient implements Callback {
    public static void main(String[] args){
        String ip = args[0];
        if(ip == null){
            System.out.println("Invalid Ip Address");
            System.exit(0);
        }
        //int port = Integer.parseInt(args[1]);
        Float threshold = 1.0f;
        if(args[1] != null)
            threshold = Float.parseFloat(args[1]);
        Integer isAtmostOne = 0;
        if(args[2]!=null)
            isAtmostOne = Integer.parseInt(args[2]);
        
        try {

            FlightClient fc = new FlightClient();
            Naming naming = new Naming();
            naming.setUpperObject(fc); //for call back
            //naming.registerSerializablePrototype()
            naming.setPort(2020);
            naming.setThreshold(threshold);
            naming.setAtMostOnce(isAtmostOne == 1);
            FlightService fs = (FlightService) naming.lookup(ip,"FlightService");
            
            //FlightList fl = fs.getIdsBySourceAndDest("Hanoi", "Singapore");
            


            System.out.println("Starting Flight Client ...");
            System.out.println("Flight Monitoring Program:");
            System.out.println("Please select one of the following options: ");
            System.out.println("1. Search flights by source and destination \n2. Get flight by Id\n3. Reserve Seats\n4. Register callback");
            System.out.println("5. Search flights on date\n6. Get the cheapest flight\n7. Discount price \n8. To exit \n");
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            int choice;
            do{
                System.out.print("Your choice: ");
                String usrIn = in.readLine();
                choice = Integer.parseInt(usrIn);
                switch(choice){
                    case 1:
                        //search flight by source and destination
                        System.out.println("Get Flights by Source and Client ...");
                        System.out.print("From: ");
                        String s = in.readLine();
                        System.out.print("To: ");
                        String d = in.readLine();
                        FlightList fl = fs.getIdsBySourceAndDest(s, d);
                        if(fl!=null)
                            System.out.println("results = " + fl);
                        else
                            System.out.println("haven't received flight list from server");
                        break;
                    case 2: 
                        //search flight by Id
                        System.out.print("Flight Id: ");
                        int id = Integer.parseInt(in.readLine());
                        Flight f = fs.getFlightById(id);
                        if(f!=null)
                            System.out.println("Result: " + f);
                        else
                            System.out.println("Error: Flight with id " + id +" doesn't exist OR haven't received reply from server");
                        break;
                    case 3: 
                        System.out.println("Reserving Seats ... ");
                        System.out.print("Flight Id: ");
                        int idd = Integer.parseInt(in.readLine());
                        System.out.print("No. Of Seats: ");
                        int noOfSeat = Integer.parseInt(in.readLine());
                        if(noOfSeat < 0){
                            System.out.println("Error: Negative Seat Number; Please try again");
                            break;
                        }
                        String res = fs.reserveSeats(idd, noOfSeat);
                        if(res!=null)
                            System.out.println("Reserved seat " + res);
                        else
                            System.out.println("haven't received reply from server");
                        break;
                    case 4: 
                        //what if call register call back twice?
                        //how to cancel ?
                        System.out.println("Registering callback ... ");
                        System.out.print("Flight Id: ");
                        Integer fid = Integer.parseInt(in.readLine());
                        System.out.print("Interval: ");
                        Integer interval = Integer.parseInt(in.readLine());
                        naming.createRegistry();
                        String mess = fs.registerCallbackFlightClient(fid, interval, fc) ;
                        if(mess == null )
                            System.out.println("haven't received reply from server");
                        else
                            System.out.println(mess);
                        if(mess!=null && mess.indexOf("success")>0){
                            System.out.println("Waiting for server call ... ");
                            Thread.sleep(interval);
                            naming.releaseRegistry();
                        }
                        break;
                    case 5:
                        //search for flight on a certain date
                        System.out.println("Searching for flight on a query date ...");
                        System.out.print("Enter date (dd/mm/yyyy): ");
                        String q = in.readLine();
                        FlightList r = fs.getFlightsOnDate(q);
                        if(r!=null)
                            System.out.println(r);
                        else
                            System.out.println("haven't received flight list from server");
                        break;
                    case 6:
                        System.out.println("Retrieving cheapest flight ... ");
                        Flight c = fs.getCheapest();
                        if(c!=null)
                            System.out.println("Cheapest is " + c);
                        else
                            System.out.println("haven't received flight from server");
                        break;
                    case 7:
                        System.out.println("Discounting airfare ... ");
                        System.out.print("Flight Id:");
                        Integer i = Integer.parseInt(in.readLine());
                        System.out.print("Discount Amount(1-100%): ");
                        Float dd = Float.parseFloat(in.readLine());
                        System.out.println(fs.discountPrice(i, dd));
                        break;
                }
            }while(choice!=8);
            

        } catch (Exception ex) {
            Logger.getLogger(FlightClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void informSeatUpdate(int newSeatNo) {
        System.out.println("Callbacked: new number of seats is "+newSeatNo);
    }

    public Object invoke(String methodName, Object[] parameters) {
        if(methodName.equalsIgnoreCase("informSeatUpdate")){
            this.informSeatUpdate((Integer)parameters[0]);
            return null;
        }
        else
            return null;
    }

    public String getIp() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
